import { Byte } from '../../api/io/Byte';
import { PlayerSnapshot } from './PlayerSnapshot';
import { ITimer } from '../../api/timer/ITimer';
import { IAsync } from '../../api/event/IAsync';



/**竞技场玩家信息属性枚举*/
export const enum E_ArenaRankPlayer {
	/**角色类型*/
	PLAYER_TYPE = 0,
	/**怪物配置id, player_type不为人的时候才有意义*/
	MONSTER_CONFIG_ID = 1,
	/**基础信息*/
	SNAPSHOT = 2,
	/**积分*/
	ARENA_SCORE = 3,
	/**战力*/
	FIGHT_SCORE = 4,
	/**排名:< 0 - 表示没有参与排名（机器人或者怪物）*/
	RANK_INDEX = 5,
	/**枚举数量*/
	EnumCount = 6
}


/**竞技场玩家信息*/
export class ArenaRankPlayer {
	/**事件ID*/
	public static readonly EVENT_ID = 'STRUCT_DATA_ARENA_RANK_PLAYER_EVENT_ID';
	/**整体更新事件ID（部分只需要监听整体变化）*/
	public static readonly TOTAL_EVENT_ID = 'STRUCT_DATA_ARENA_RANK_PLAYER_TOTAL_EVENT_ID';
	/**缓存池*/
	private static POOL: ArenaRankPlayer[] = [];

	/**创建入口*/
	public static create(json?: string): ArenaRankPlayer {
		const c = this.POOL.pop() || new ArenaRankPlayer();
		c._destroyed = false;
		c.resetProperty();
		if (json) {
			c.parse(json);
		}
		return c;
	}


	/**已释放*/
	protected _destroyed = false;
	/**角色类型 (uint8)*/
	protected _playerType: number;
	/**怪物配置id, player_type不为人的时候才有意义 (uint32)*/
	protected _monsterConfigId: number;
	/**基础信息*/
	protected _snapshot: PlayerSnapshot = null;
	/**积分 (long)*/
	protected _arenaScore: number;
	/**战力 (long)*/
	protected _fightScore: number;
	/**排名:< 0 - 表示没有参与排名（机器人或者怪物） (uint16)*/
	protected _rankIndex: number;


	/**构建函数-私有，防止外部创建*/
	private constructor() {
	}


	/**释放*/
	public destroy(): void {
		if (this._destroyed) {
			return;
		}
		this._destroyed = true;
		this.resetProperty(true);
		if (ArenaRankPlayer.POOL.indexOf(this) === -1) {
			ArenaRankPlayer.POOL.push(this);
		}
	}

	/**角色类型*/
	public get playerType() {
		return this._playerType;
	}


	/**角色类型*/
	public set playerType(v: number) {
		this._playerType = v;
	}


	/**怪物配置id, player_type不为人的时候才有意义*/
	public get monsterConfigId() {
		return this._monsterConfigId;
	}


	/**怪物配置id, player_type不为人的时候才有意义*/
	public set monsterConfigId(v: number) {
		this._monsterConfigId = v;
	}


	/**基础信息*/
	public get snapshot() {
		return this._snapshot;
	}


	/**积分*/
	public get arenaScore() {
		return this._arenaScore;
	}


	/**积分*/
	public set arenaScore(v: number) {
		this._arenaScore = v;
	}


	/**战力*/
	public get fightScore() {
		return this._fightScore;
	}


	/**战力*/
	public set fightScore(v: number) {
		this._fightScore = v;
	}


	/**排名:< 0 - 表示没有参与排名（机器人或者怪物）*/
	public get rankIndex() {
		return this._rankIndex;
	}


	/**排名:< 0 - 表示没有参与排名（机器人或者怪物）*/
	public set rankIndex(v: number) {
		this._rankIndex = v;
	}



	/**通过枚举获取值*/
	public getV(k: E_ArenaRankPlayer): any {
		switch (k) {
			case E_ArenaRankPlayer.PLAYER_TYPE: return this._playerType;
			case E_ArenaRankPlayer.MONSTER_CONFIG_ID: return this._monsterConfigId;
			case E_ArenaRankPlayer.SNAPSHOT: return this._snapshot;
			case E_ArenaRankPlayer.ARENA_SCORE: return this._arenaScore;
			case E_ArenaRankPlayer.FIGHT_SCORE: return this._fightScore;
			case E_ArenaRankPlayer.RANK_INDEX: return this._rankIndex;
			default: return null;
		}
	}


	/**通过枚举设置值*/
	public setV(k: E_ArenaRankPlayer, v: any): void {
		switch (k) {
			case E_ArenaRankPlayer.PLAYER_TYPE: this._playerType = v; break;
			case E_ArenaRankPlayer.MONSTER_CONFIG_ID: this._monsterConfigId = v; break;
			case E_ArenaRankPlayer.SNAPSHOT: this._snapshot = v; break;
			case E_ArenaRankPlayer.ARENA_SCORE: this._arenaScore = v; break;
			case E_ArenaRankPlayer.FIGHT_SCORE: this._fightScore = v; break;
			case E_ArenaRankPlayer.RANK_INDEX: this._rankIndex = v; break;
			default: break;
		}
	}


	/**初始化*/
	public resetProperty(fromDestroy = false): void {
		//角色类型
		this._playerType = 0;
		//怪物配置id, player_type不为人的时候才有意义
		this._monsterConfigId = 0;
		//基础信息
		if (this._snapshot) {
			this._snapshot.destroy();
			this._snapshot = null;
		}
		if (!fromDestroy) {
			this._snapshot = PlayerSnapshot.create();
		}
		//积分
		this._arenaScore = 0;
		//战力
		this._fightScore = 0;
		//排名:< 0 - 表示没有参与排名（机器人或者怪物）
		this._rankIndex = 0;
	}


	/**序列化*/
	public stringify(toString: boolean): string | any {
		const json: any = {};
		if (this._playerType) {
			json.playerType = this._playerType;
		}
		if (this._monsterConfigId) {
			json.monsterConfigId = this._monsterConfigId;
		}
		if (this._snapshot) {
			json.snapshot = this._snapshot.stringify(false);
		}
		if (this._arenaScore) {
			json.arenaScore = this._arenaScore;
		}
		if (this._fightScore) {
			json.fightScore = this._fightScore;
		}
		if (this._rankIndex) {
			json.rankIndex = this._rankIndex;
		}

		return toString ? JSON.stringify(json) : json;
	}


	/**反序列化*/
	public parse(jsonv: string | any): this {
		this.resetProperty();
		if (!jsonv) {
			return this;
		}
		const json = typeof (jsonv) === 'string' ? JSON.parse(jsonv) : jsonv;
		if (json.playerType) {
			this._playerType = json.playerType;
		}
		if (json.monsterConfigId) {
			this._monsterConfigId = json.monsterConfigId;
		}
		if (json.snapshot) {
			this._snapshot.destroy();
			this._snapshot = PlayerSnapshot.create(json.snapshot);
		}
		if (json.arenaScore) {
			this._arenaScore = json.arenaScore;
		}
		if (json.fightScore) {
			this._fightScore = json.fightScore;
		}
		if (json.rankIndex) {
			this._rankIndex = json.rankIndex;
		}
		return this;
	}


	/**序列化-二进制*/
	public toBytes(byte: Byte): void {
		if (!byte) {
			return;
		}
		byte.writeUint8(this._playerType);
		byte.writeUint32(this._monsterConfigId);
		this._snapshot.toBytes(byte);
		byte.writeLongNumber(this._arenaScore);
		byte.writeLongNumber(this._fightScore);
		byte.writeUint16(this._rankIndex);
	}


	/**反序列化-二进制*/
	public fromBytes(byte: Byte): this {
		this.resetProperty();
		if (!byte) {
			return;
		}
		this._playerType = byte.readUint8();
		this._monsterConfigId = byte.readUint32();
		this._snapshot.fromBytes(byte);
		this._arenaScore = byte.readLongNumber();
		this._fightScore = byte.readLongNumber();
		this._rankIndex = byte.readUint16();
		return this;
	}


	/**克隆*/
	public clone(): ArenaRankPlayer {
		const byte = Byte.createFromPool();
		this.toBytes(byte);
		byte.pos = 0;
		const clonev = ArenaRankPlayer.create().fromBytes(byte);
		Byte.recoverToPool(byte);
		return clonev;
	}


	/**处理更新*/
	public processUpdate(jsonv: string): void {
		if (!jsonv) {
			return;
		}

		const eventID = ArenaRankPlayer.EVENT_ID;
		const us = JSON.parse(jsonv);

		for (let i = 0, len = us.length; i < len;) {
			const idx = us[i];
			//角色类型
			if (idx === E_ArenaRankPlayer.PLAYER_TYPE) {
				const oldv = this._playerType;
				this._playerType = us[i + 1];
				IAsync.dispatch(eventID, idx, this._playerType, oldv);
				i += 2;
				continue;
			}
			//怪物配置id, player_type不为人的时候才有意义
			if (idx === E_ArenaRankPlayer.MONSTER_CONFIG_ID) {
				const oldv = this._monsterConfigId;
				this._monsterConfigId = us[i + 1];
				IAsync.dispatch(eventID, idx, this._monsterConfigId, oldv);
				i += 2;
				continue;
			}
			//基础信息
			if (idx === E_ArenaRankPlayer.SNAPSHOT) {
				const fui: string = us[i + 1];
				if (this._snapshot) {
					this._snapshot.processUpdate(fui);
				}
				else {
					console.error('ArenaRankPlayer snapshot is null when update.');
				}
				IAsync.dispatch(eventID, idx);
				i += 2;
				continue;
			}
			//积分
			if (idx === E_ArenaRankPlayer.ARENA_SCORE) {
				const oldv = this._arenaScore;
				this._arenaScore = us[i + 1];
				IAsync.dispatch(eventID, idx, this._arenaScore, oldv);
				i += 2;
				continue;
			}
			//战力
			if (idx === E_ArenaRankPlayer.FIGHT_SCORE) {
				const oldv = this._fightScore;
				this._fightScore = us[i + 1];
				IAsync.dispatch(eventID, idx, this._fightScore, oldv);
				i += 2;
				continue;
			}
			//排名:< 0 - 表示没有参与排名（机器人或者怪物）
			if (idx === E_ArenaRankPlayer.RANK_INDEX) {
				const oldv = this._rankIndex;
				this._rankIndex = us[i + 1];
				IAsync.dispatch(eventID, idx, this._rankIndex, oldv);
				i += 2;
				continue;
			}

			console.error('[Struct Data] can not find enum in ArenaRankPlayer with idx = ' + idx + ', version maybe wrong.')
		}

		//全更事件
		ITimer.callLater(this, this.dispatchTotalUpdate);
	}


	/**比对不一致结果*/
	public getCompareInfo(other: ArenaRankPlayer): string {
		if (!other) {
			return null;
		}

		const updates: any[] = [];

		if (this._playerType !== other._playerType) {
			updates.push(E_ArenaRankPlayer.PLAYER_TYPE, this._playerType);
		}
		if (this._monsterConfigId !== other._monsterConfigId) {
			updates.push(E_ArenaRankPlayer.MONSTER_CONFIG_ID, this._monsterConfigId);
		}
		//基础信息
		{
			const ui = this._snapshot.getCompareInfo(other._snapshot);
			if (ui && ui.length > 0) {
				updates.push(E_ArenaRankPlayer.SNAPSHOT, ui);
			}
		}
		if (this._arenaScore !== other._arenaScore) {
			updates.push(E_ArenaRankPlayer.ARENA_SCORE, this._arenaScore);
		}
		if (this._fightScore !== other._fightScore) {
			updates.push(E_ArenaRankPlayer.FIGHT_SCORE, this._fightScore);
		}
		if (this._rankIndex !== other._rankIndex) {
			updates.push(E_ArenaRankPlayer.RANK_INDEX, this._rankIndex);
		}

		const jsonv = updates.length === 0 ? null : JSON.stringify(updates);
		return jsonv;
	}


	/**全部更新*/
	protected dispatchTotalUpdate(): void {
		IAsync.dispatch(ArenaRankPlayer.TOTAL_EVENT_ID, this.getV(0));
	}

}
